package com.wash.shoes.oss;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.UUID;

/**
 * Created by lightClouds917
 * Date 2018/2/7
 * Description:aliyunOSSUtil
 */
public class AliyunOSSUtil {

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(AliyunOSSUtil.class);

    public static String makeObjName1(String prefix, String suffix) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime now = LocalDateTime.now();
        String format = df.format(now);
        return prefix + "/" + format + "/" + UUID.randomUUID().toString().replaceAll("-", "") + "." + suffix;
    }

    /**
     * @添加图片
     */
    public static String addPicPObj(String objName, InputStream is) {
        OSSClient ossClient = init();

        try {
            try {
                ossClient.putObject(ConstantProperties.BUCKETNAME, objName, is);
                try {
                    is.close();
                } catch (IOException e) {
                    logger.error("", e);
                }
            } catch (OSSException | ClientException e) {
                logger.error("", e);
                System.out.println("添加object\t" + objName + "\t异常。");
                return null;
            }
            return "http://" + ConstantProperties.BUCKETNAME + "." + ConstantProperties.ENDPOINT + "/" + objName;

        } catch (ClientException e) {
            logger.error("", e);
        } finally {
            ossClient.shutdown();
        }
        return null;
    }

    public static OSSClient init() {
        String endpoint = ConstantProperties.ENDPOINT;
        String accessKeyId = ConstantProperties.KEYID;
        String accessKeySecret = ConstantProperties.KEYSECRET;
        String bucketName = ConstantProperties.BUCKETNAME;
        String fileHost = ConstantProperties.FILEHOST;
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        return ossClient;
    }

    public static String uploadMFile(MultipartFile multipartFile) throws IOException {

        String filename = multipartFile.getOriginalFilename() + ".jpg";
        String uploadUrl = null;
        if (!filename.trim().isEmpty()) {
            File newFile = new File(filename);
            FileOutputStream os = new FileOutputStream(newFile);
            os.write(multipartFile.getBytes());
            os.close();
            multipartFile.transferTo(newFile);
            //上传到OSS
            String url = AliyunOSSUtil.upload(newFile, null);
            FileUtil.del(newFile);
            return url;
        }
        return null;
    }


    public static String upload(File file, String basePath) {

        logger.info("=========>OSS文件上传开始：" + file.getName());

        OSSClient ossClient = init();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = format.format(new Date());

        try {
            //容器不存在，就创建
            if (!ossClient.doesBucketExist(ConstantProperties.BUCKETNAME)) {
                ossClient.createBucket(ConstantProperties.BUCKETNAME);
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(ConstantProperties.BUCKETNAME);
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                ossClient.createBucket(createBucketRequest);
            }
            //创建文件路径
            String fileUrl;
            if (StrUtil.isBlank(basePath)) {
                fileUrl = ConstantProperties.FILEHOST + "/" + (dateStr + "/" + UUID.randomUUID().toString().replace("-", "") + "-" + file.getName());
            } else {
                fileUrl = basePath + "/" + (dateStr + "/" + UUID.randomUUID().toString().replace("-", "") + "-" + file.getName());

            }
            //上传文件
            PutObjectResult result = ossClient.putObject(new PutObjectRequest(ConstantProperties.BUCKETNAME, fileUrl, file));
            //设置权限 这里是公开读
            //ossClient.setBucketAcl(ConstantProperties.BUCKETNAME,CannedAccessControlList.PublicRead);
            if (null != result) {
                logger.info("==========>OSS文件上传成功,OSS地址：" + fileUrl);
                return fileUrl;
            }
        } catch (OSSException oe) {
            logger.error(oe.getMessage());
        } catch (ClientException ce) {
            logger.error(ce.getMessage());
        } finally {
            //关闭
            ossClient.shutdown();
        }
        return null;
    }
}